package jsyf.oa.service.report.newAppReport;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.report.newAppReport.NewAppReportForZSQDao;
import jsyf.oa.dao.system.*;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.facade.report.newAppReport.NewAppReportForZSQFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@SuppressWarnings("all")
@Service
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class NewAppReportForZSQService implements NewAppReportForZSQFacade {

    @Autowired
    private NewAppReportForZSQDao newAppReportForZSQDao;
    @Autowired
    private CheckDao checkDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private TokenDao tokenDao;

    private String getRegionManagerByUserId(String userId, StringBuffer condition, Boolean flag) {
        String userIdList = "";
        String userIds = checkDao.getChilderByUserId(userId, true);
        if (flag) {
            String resignationUserId = checkDao.getResignationByUserIdFroBRM(userId, true);
            if (!"''".equals(resignationUserId)) {
                userIds += "," + resignationUserId;
            }
        }
        Calendar c = Calendar.getInstance();
        String dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        List<JSONObject> userIdsList = newAppReportForZSQDao.getRegionManagerByUserId(userIds, dateTime, condition);
        if (null != userIdsList && userIdsList.size() > 0) {
            for (int i = 0; i < userIdsList.size(); i++) {
                userIdList += "'" + userIdsList.get(i).getString("userId") + "',";
            }
        } else {
            userIdList = "'',";
        }
        return userIdList = userIdList.substring(0, userIdList.length() - 1);
    }

    @Override
    public JSONObject getTodayPlanByUserIdAndDateTimeForZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        dateTime = DateUtils.getyesterdayByDateTime(dateTime);
        String roleName = userDao.getViewByUserId(" AND ID=?", new Object[]{userId}).get(0).getString("roleName");
        StringBuffer condition = new StringBuffer();
        StringBuffer roleNames = getRoleNamesByRoleName(roleName);
        if (roleNames.length() < 3) {
            condition = null;
        } else {
            condition.append(" AND roleName in (\n");
            condition.append(roleNames);
            condition.append(" ) and main=1 \n");
        }
        String userIds = getRegionManagerByUserId(userId, condition, false);
        List<JSONObject> records = newAppReportForZSQDao.getTodayPlanByUserIdAndDateTimeForZSQ(userIds, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject getTodaySignForZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");

        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        String roleName = userDao.getViewByUserId(" AND ID=?", new Object[]{userId}).get(0).getString("roleName");
        StringBuffer condition = new StringBuffer();
        StringBuffer roleNames = getRoleNamesByRoleName(roleName);
        if (roleNames.length() < 3) {
            condition = null;
        } else {
            condition.append(" AND roleName in (\n");
            condition.append(roleNames);
            condition.append(" )\n");
        }
        String userIds = getRegionManagerByUserId(userId, condition, false);
        List<JSONObject> jsonObject = new ArrayList<JSONObject>();

        //获取个人考勤信息,判断出勤、缺勤、请假
        List<JSONObject> signToday = newAppReportForZSQDao.getSignAndLeaveForToday(userIds, dateTime);
        if (null != signToday && signToday.size() > 0) {
            for (int i = 0; i < signToday.size(); i++) {
                //1签到/2缺勤/0请假
                JSONObject result = new JSONObject();
                String signCreateTime = signToday.get(i).getString("signCreateTime");
                String beginTime = signToday.get(i).getString("beginTime");
                if (StringUtils.isBlank(signCreateTime) && StringUtils.isBlank(beginTime)) {
                    JSONObject userObject = new JSONObject();
                    userObject.put("userName", userDao.getById(signToday.get(i).getString("userId")).getName());
                    userObject.put("userId", userId);
                    result.put("signState", "2");
                    result.put("result", userObject);
                    jsonObject.add(result);
                }
                if (StringUtils.isNotEmpty(signCreateTime) && StringUtils.isBlank(beginTime)) {
                    result.put("signState", "1");
                    result.put("result", signToday.get(i));
                    jsonObject.add(result);
                }
                if (StringUtils.isNotEmpty(beginTime) && StringUtils.isBlank(signCreateTime)) {
                    result.put("signState", "0");
                    result.put("result", signToday.get(i));
                    jsonObject.add(result);
                }

            }
        }
        JSONObject result = new JSONObject();
        result.put("records", jsonObject);
        return result;
    }

    @Override
    public JSONObject getTodayFirstVisitAndSignForZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }

        String userIds = getRegionManagerByUserId(userId, null, false);
        List<JSONObject> firstVisitAndSignList = newAppReportForZSQDao.getFirstVisitAndSignForToday(userIds, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", firstVisitAndSignList);
        return result;
    }

    @Override
    public JSONObject getBRMTodayFirstVisitAndSignForZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        StringBuffer condition = new StringBuffer();
        condition.append(" and roleName='大区经理'\n");
        String userIds = getRegionManagerByUserId(userId, condition, false);
        List<JSONObject> firstVisitAndSignList = newAppReportForZSQDao.getFirstVisitAndSignForToday(userIds, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", firstVisitAndSignList);
        return result;
    }

    @Override
    public JSONObject getTodayFirstVisitAndSignForBRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        StringBuffer condition = new StringBuffer();
        condition.append(" and roleName in ('区域经理','区域组长')\n");
        String userIds = getRegionManagerByUserId(userId, condition, false);
        List<JSONObject> firstVisitAndSignList = newAppReportForZSQDao.getFirstVisitAndSignForToday(userIds, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", firstVisitAndSignList);
        return result;
    }

    @Override
    public JSONObject getVisitByUserIdAndDateTimeForZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String type = jsonParams.getString("type");//0-电/1-面
        String status = jsonParams.getString("status");//0-AM/1-PM
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }

        String userIds = getRegionManagerByUserId(userId, null, false);

        List<JSONObject> jsonObjects = newAppReportForZSQDao.getForPersonalDayByUserIdAndDateTime(userIds, dateTime, Integer.valueOf(type), Integer.valueOf(status));
        JSONObject result = new JSONObject();
        result.put("records", jsonObjects);
        return result;
    }

    @Override
    public JSONObject getCostByUserIdAndDateTimeForZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        String roleName = userDao.getViewByUserId(" AND ID=?", new Object[]{userId}).get(0).getString("roleName");
        StringBuffer condition = new StringBuffer();
        if ("区域支持".equals(roleName) || "销售管理".equals(roleName)) {
            roleName = "大区经理";
        }
        StringBuffer roleNames = getRoleNamesByRoleName(roleName);
        if (roleNames.length() < 3) {
            condition = null;
        } else {
            condition.append(" AND roleName in (\n");
            condition.append(roleNames);
            condition.append(" )\n");
        }
        String userIds = getRegionManagerByUserId(userId, condition, false);
        List<JSONObject> personalCostList = newAppReportForZSQDao.getForPersonalCostByUserIdAndDateTime(userIds, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", personalCostList);
        return result;
    }

    @Override
    public JSONObject getEmailByUserIdForZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String roleName = userDao.getViewByUserId(" AND ID=? AND MAIN=1", new Object[]{userId}).get(0).getString("roleName");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        dateTime = DateUtils.getyesterdayByDateTime(dateTime);

        StringBuffer condition = new StringBuffer();
        StringBuffer roleNames = getRoleNamesByRoleName(roleName);
        if (roleNames.length() < 3) {
            condition = null;
        } else {
            condition.append(" AND roleName in (\n");
            condition.append(roleNames);
            condition.append(" )\n");
        }
        String userIds = getRegionManagerByUserId(userId, condition, false);

        List<JSONObject> list = newAppReportForZSQDao.getEmailByUserIdForZSQ(userIds, dateTime, userId, condition);

        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;

    }

    @Override
    public JSONObject getLeaveReasonByUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }

        List<JSONObject> list = newAppReportForZSQDao.getLeaveReasonByUserId(userId, dateTime);

        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;

    }

    @Override
    public List<JSONObject> getCalendar(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        }
        String beforeTime = DateUtils.getBeforeMonth(newAppReportForZSQDao.getCurrentTime());
        List result = newAppReportForZSQDao.getCalendar(userId, dateTime, beforeTime);
        return result;
    }


    @Override
    public JSONObject getSignByMyself(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        JSONObject result = newAppReportForZSQDao.getSignByMyself(userId, dateTime);
        return result;
    }

    @Override
    public JSONObject getVisitByUserIdAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String type = jsonParams.getString("type");//0-电/1-面
        String status = jsonParams.getString("status");//0-AM/1-PM

        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!StringUtils.isBlank(jsonParams.getString("pageSize"))) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (!StringUtils.isBlank(jsonParams.getString("requestPage"))) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        String nowTime = "";
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            nowTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        } else {
            nowTime = dateTime.substring(0, 7);
        }
        String key = "";
        if (jsonParams.containsKey("key")) {
            key = jsonParams.getString("key");
        }
        StringBuffer condition = new StringBuffer();
        condition.append(" AND (t_wrt_customer.`NAME` LIKE  '%" + key + "%'\n" +
                "OR t_wrt_customer. TEL LIKE '%" + key + "%'\n" +
                "OR t_wrt_customer.`WECHAT` LIKE '%" + key + "%'\n" +
                ")\n");
        List<JSONObject> jsonObjects = newAppReportForZSQDao.getForPersonalDayByUserIdAndDateTime(userId, dateTime, Integer.valueOf(type), Integer.valueOf(status), condition, requestPage, pageSize);
        int recordCount = newAppReportForZSQDao.getForPersonalDayByUserIdAndDateTimePageCount(userId, dateTime, Integer.valueOf(type), Integer.valueOf(status), condition);

        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);
        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", jsonObjects);
        objResult.put("pager", objPager);

        return objResult;
    }

    //大区经理工作报告
    @Override
    public JSONObject getBRMEmailForZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String roleName = jsonParams.getString("roleName");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        dateTime = DateUtils.getyesterdayByDateTime(dateTime);

        StringBuffer condition = new StringBuffer();
        condition.append(" AND roleName ='大区经理'  AND v_sys_user.MAIN=1 \n");

        String senderIds = getRegionManagerByUserId(userId, condition, false);
        String receiverIds = "";
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and id in (" + senderIds + ") and main = 1", new Object[]{});
        if (null != userList && userList.size() > 0) {
            for (int i = 0; i < userList.size(); i++) {
                receiverIds += "'" + userList.get(i).getString("parentId") + "',";
            }
        }
        if (!StringUtils.isBlank(receiverIds) && receiverIds.endsWith(",")) {
            receiverIds = receiverIds.substring(0, receiverIds.length() - 1);
        } else {
            receiverIds = "''";
        }


        if (StringUtils.isBlank(senderIds)) {
            senderIds = "''";
        }
        List<JSONObject> list = newAppReportForZSQDao.getEmailForZSQ(userId, senderIds, receiverIds, dateTime);
        if (null != list && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject object = list.get(i);
                String readerId = object.getString("readerId");
                if (StringUtils.isBlank(readerId)) {
                    String regionId = object.getString("regionId");
                    String companyId = object.getString("companyId");
                    readerId = getReader("区域总监", regionId, companyId);
                    if (!StringUtils.isBlank(readerId)) {
                        object.put("readerId", readerId);
                        object.put("readerName", userDao.getById(readerId).getName());
                    }
                    if ("未发送".equals(object.getString("titleSend"))) {
                        Integer count = newAppReportForZSQDao.getSendEmail(object.getString("userId"), dateTime);
                        if (null != count && count != 0) {
                            object.put("titleSend", "已发送");
                        }
                    }
                }
            }
        }

        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;

    }

    //区域总监工作报告
    @Override
    public JSONObject getRDEmailForZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject result = new JSONObject();

        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String roleName = jsonParams.getString("roleName");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        dateTime = DateUtils.getyesterdayByDateTime(dateTime);

        StringBuffer condition = new StringBuffer();
        condition.append(" AND roleName ='区域总监'  AND v_sys_user.MAIN=1 \n");

        String senderIds = getRegionManagerByUserId(userId, condition, false);

        if (StringUtils.isBlank(senderIds) || senderIds.length() < 3) {
            result.put("records", null);
            return result;
        }
        String receiverIds = "";
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and id in (" + senderIds + ") and main = 1", new Object[]{});
        if (null != userList && userList.size() > 0) {
            for (int i = 0; i < userList.size(); i++) {
                receiverIds += "'" + userList.get(i).getString("parentId") + "',";
            }
        }
        if (!StringUtils.isBlank(receiverIds) && receiverIds.endsWith(",")) {
            receiverIds = receiverIds.substring(0, receiverIds.length() - 1);
        } else {
            receiverIds = "''";
        }
        if (StringUtils.isBlank(senderIds)) {
            senderIds = "''";
        }
        List<JSONObject> list = newAppReportForZSQDao.getUserRegionEmailForZSQ(userId, senderIds, receiverIds, dateTime);

        if (null != list && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject object = list.get(i);
                String readerId = object.getString("readerId");
                if (StringUtils.isBlank(readerId)) {
                    String sendId = object.getString("userId");
                    readerId = userDao.getById(sendId).getParentId();
                    if (!StringUtils.isBlank(readerId)) {
                        object.put("readerId", readerId);
                        object.put("readerName", userDao.getById(readerId).getName());
                    }
                    if ("未发送".equals(object.getString("titleSend"))) {
                        Integer count = newAppReportForZSQDao.getSendEmail(object.getString("userId"), dateTime);
                        if (null != count && count != 0) {
                            object.put("titleSend", "已发送");
                        }
                    }
                }
            }
        }
        result.put("records", list);
        return result;

    }

    //销售总监工作报告
    @Override
    public JSONObject getSDEmailForZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject result = new JSONObject();

        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String roleName = jsonParams.getString("roleName");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        dateTime = DateUtils.getyesterdayByDateTime(dateTime);

        StringBuffer condition = new StringBuffer();
        condition.append(" AND roleName ='销售总监'  AND v_sys_user.MAIN=1 \n");

        String senderIds = getRegionManagerByUserId(userId, condition, false);

        if (StringUtils.isBlank(senderIds) || senderIds.length() < 3) {
            result.put("records", null);
            return result;
        }
        String receiverIds = "";
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and id in (" + senderIds + ") and main = 1", new Object[]{});
        if (null != userList && userList.size() > 0) {
            for (int i = 0; i < userList.size(); i++) {
                receiverIds += "'" + userList.get(i).getString("parentId") + "',";
            }
        }
        if (!StringUtils.isBlank(receiverIds) && receiverIds.endsWith(",")) {
            receiverIds = receiverIds.substring(0, receiverIds.length() - 1);
        } else {
            receiverIds = "''";
        }
        if (StringUtils.isBlank(senderIds)) {
            senderIds = "''";
        }
        List<JSONObject> list = newAppReportForZSQDao.getUserRegionEmailForZSQ(userId, senderIds, receiverIds, dateTime);

        if (null != list && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject object = list.get(i);
                String readerId = object.getString("readerId");
                if (StringUtils.isBlank(readerId)) {
                    String sendId = object.getString("userId");
                    readerId = userDao.getById(sendId).getParentId();
                    if (!StringUtils.isBlank(readerId)) {
                        object.put("readerId", readerId);
                        object.put("readerName", userDao.getById(readerId).getName());
                    }
                    if ("未发送".equals(object.getString("titleSend"))) {
                        Integer count = newAppReportForZSQDao.getSendEmail(object.getString("userId"), dateTime);
                        if (null != count && count != 0) {
                            object.put("titleSend", "已发送");
                        }
                    }
                }
            }
        }
        result.put("records", list);
        return result;

    }

    //区域总监考勤
    @Override
    public JSONObject getSignByUserIdAndDateTimeForZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        List<JSONObject> list = newAppReportForZSQDao.getSginForZSQ(userId, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;
    }

    @Override
    public JSONObject getSignForZZRegionZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        List<JSONObject> list = newAppReportForZSQDao.getSignForZZRegionZSQ(userId, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;
    }

    //总经理考勤
    @Override
    public JSONObject getSignByUserIdAndDateTimeForTOPZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        List<JSONObject> list = newAppReportForZSQDao.getSginForTOPZSQ(userId, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;
    }

    @Override
    public JSONObject getSignByUserIdAndDateTimeForXSZJZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        JSONObject user = userDao.getViewJSONById(userId);
        List<JSONObject> list = newAppReportForZSQDao.getSginForXSZJZSQ(user.getString("companyId"), dateTime);
        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;
    }

    @Override
    public JSONObject getSignByUserIdAndDateTimeForQYZCZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        List<JSONObject> list = newAppReportForZSQDao.getSginForQYZCZSQ(userId, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;
    }

    @Override
    public JSONObject getSignByBigUserIdAndDateTimeForZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        List<JSONObject> list = newAppReportForZSQDao.getBigRegionForZSQ(userId);
        List<JSONObject> listBigRegion = newAppReportForZSQDao.getBigRegionForZSQ(userId, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", list);
        result.put("recordsBigRegion", listBigRegion);
        return result;
    }

    //获取区域
    @Override
    public JSONObject getRegionIdByUserIdForZSQ(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");

        List<JSONObject> list = newAppReportForZSQDao.getRegionIdByUserIdForZSQ(userId);

        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;

    }

    //获取RoleName
    @Override
    public JSONObject getRoleNameByUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String roleName = userDao.getViewByUserId(" and id = ? ", new Object[]{userId}).get(0).getString("roleName");
        JSONObject result = new JSONObject();
        result.put("records", roleName);
        return result;

    }

    //销售管理看销售总监工作报告
    @Override
    public JSONObject getSDEmailForXM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject result = new JSONObject();
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        dateTime = DateUtils.getyesterdayByDateTime(dateTime);
        StringBuffer condition = new StringBuffer();
        condition.append(" AND roleName ='销售总监' \n");

        String senderIds = getRegionManagerByUserId(userId, condition, false);
        if (StringUtils.isBlank(senderIds) || senderIds.length() < 3) {
            result.put("records", null);
            return result;
        }

        String receiverIds = "'" + userId + "'";

        if (StringUtils.isBlank(senderIds)) {
            senderIds = "''";
        }
        if (StringUtils.isBlank(receiverIds)) {
            receiverIds = "''";
        }
        List<JSONObject> list = newAppReportForZSQDao.getEmailForSupport2(senderIds, receiverIds, dateTime);

        if (null != list && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject object = list.get(i);
                String readerId = object.getString("readerId");
                if (StringUtils.isBlank(readerId)) {
                    object.put("readerId", userId);
                    object.put("readerName", userDao.getById(userId).getName());
                    if ("未发送".equals(object.getString("titleSend"))) {
                        Integer count = newAppReportForZSQDao.getSendEmail(object.getString("userId"), dateTime);
                        if (null != count && count != 0) {
                            object.put("titleSend", "已发送");
                        }
                    }
                }
            }
        }

        result.put("records", list);
        return result;
    }

    //区域支持查看区域总监工作报告
    @Override
    public JSONObject getRDEmailForRS(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        List<JSONObject> list = new ArrayList<>();
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        dateTime = DateUtils.getyesterdayByDateTime(dateTime);
        StringBuffer condition = new StringBuffer();
        condition.append(" AND roleName ='区域总监'  AND v_sys_user.MAIN=1 \n");

        String senderIds = getRegionManagerByUserId(userId, condition, false);

        Map<String, JSONObject> userRegion = new HashMap<>();
        if (!StringUtils.isBlank(senderIds) && senderIds.length() > 3) {
            String[] senderIdsArray = senderIds.split(",");
            if (null != senderIdsArray && senderIdsArray.length > 0) {
                for (int i = 0; i < senderIdsArray.length; i++) {
                    String senderUserId = senderIdsArray[i];
                    String senderUserName = userDao.getById(senderUserId.substring(1, senderUserId.length() - 1)).getName();
                    List<JSONObject> regionIdsForSBXQ = newAppReportForZSQDao.getRegionIdByUserIdForSBXQ(senderUserId);
                    if (null != regionIdsForSBXQ && regionIdsForSBXQ.size() > 0) {
                        String regionId = "";
                        String regionName = "";
                        for (int j = 0; j < regionIdsForSBXQ.size(); j++) {
                            JSONObject regionTemp1 = regionIdsForSBXQ.get(j);
                            regionId += "'" + regionTemp1.getString("regionId") + "',";
                            regionName += regionTemp1.getString("regionName") + "/";
                        }
                        if (!StringUtils.isBlank(regionId) && regionId.endsWith(",")) {
                            regionId = regionId.substring(0, regionId.length() - 1);
                        } else {
                            regionId = "''";
                        }
                        if (!StringUtils.isBlank(regionName) && regionName.endsWith("/")) {
                            regionName = regionName.substring(0, regionName.length() - 1);
                        } else {
                            regionName = "''";
                        }
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("regionId", regionId);
                        jsonObject.put("regionName", regionName);
                        userRegion.put(senderUserId, jsonObject);
                    }
                    JSONObject jsonObjectTemp1 = userRegion.get(senderUserId);
                    if (null != jsonObjectTemp1) {
                        List<JSONObject> rsUserIds = newAppReportForZSQDao.getRSByRegionIdForSBXQ(jsonObjectTemp1.getString("regionId"));
                        if (null != rsUserIds && rsUserIds.size() > 0) {
                            for (int j = 0; j < rsUserIds.size(); j++) {
                                JSONObject jsonObjectTemp2 = rsUserIds.get(j);
                                String rsUserId = jsonObjectTemp2.getString("userId");
                                String rsUserName = jsonObjectTemp2.getString("userName");
                                JSONObject jsonObject = newAppReportForZSQDao.getEmailForSupport1(senderUserId, rsUserId, dateTime);
                                if (null != jsonObject) {
                                    jsonObject.put("userId", senderUserId.substring(1, senderUserId.length() - 1));
                                    jsonObject.put("userName", senderUserName);
                                    jsonObject.put("readerId", rsUserId);
                                    jsonObject.put("readerName", userDao.getById(rsUserId).getName());
                                    jsonObject.put("regionName", jsonObjectTemp1.getString("regionName"));
                                    if ("未发送".equals(jsonObject.getString("titleSend"))) {
                                        Integer count = newAppReportForZSQDao.getSendEmail(jsonObject.getString("userId"), dateTime);
                                        if (null != count && count != 0) {
                                            jsonObject.put("titleSend", "已发送");
                                        }
                                    }
                                    list.add(jsonObject);
                                }
                            }
                        }
                    }
                }
            }
        }
        Comparator<JSONObject> comparator = new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject jsonObject1, JSONObject jsonObject2) {
                if (null == jsonObject1 || null == jsonObject2) {
                    return -1;
                }
                if (!jsonObject1.getString("readerId").equals(jsonObject2.getString("readerId"))) {

                    return jsonObject1.getString("readerId").compareTo(jsonObject2.getString("readerId"));
                } else {

                    return 1;
                }
            }
        };
        Collections.sort(list, comparator);

        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;
    }

    //区域支持工作报告
    @Override
    public JSONObject getRSEmailForXM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        dateTime = DateUtils.getyesterdayByDateTime(dateTime);
        StringBuffer condition = new StringBuffer();
        condition.append(" AND roleName in ('区域支持','办事处支持','销售支持')  AND v_sys_user.MAIN=1 \n");

        String senderIds = getRegionManagerByUserId(userId, condition, false);
        if (StringUtils.isBlank(senderIds)) {
            senderIds = "''";
        }

        String receiverIds = "'" + userId + "'";

        List<JSONObject> list = newAppReportForZSQDao.getUserRegionEmailForZSQ(userId, senderIds, receiverIds, dateTime);

        if (null != list && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject object = list.get(i);
                String readerId = object.getString("readerId");
                if (StringUtils.isBlank(readerId)) {
                    String regionId = object.getString("regionId");
                    String companyId = object.getString("companyId");
                    readerId = getSupportReader("销售管理", regionId, companyId);
                    if (!StringUtils.isBlank(readerId)) {
                        object.put("readerId", readerId);
                        object.put("readerName", userDao.getById(readerId).getName());
                    }
                    if ("未发送".equals(object.getString("titleSend"))) {
                        Integer count = newAppReportForZSQDao.getSendEmail(object.getString("userId"), dateTime);
                        if (null != count && count != 0) {
                            object.put("titleSend", "已发送");
                        }
                    }
                }
            }
        }

        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;

    }

    //区域经理工作报告
    @Override
    public JSONObject getEmailByUserIdForRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String regionId = jsonParams.getString("regionId");
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        dateTime = DateUtils.getyesterdayByDateTime(dateTime);
        StringBuffer condition = new StringBuffer();
        condition.append(" AND roleName in ('区域经理','区域组长')  AND v_sys_user.MAIN=1 \n");

        String userIds = getRegionManagerByUserId(userId, condition, false);

        List<JSONObject> qyList = newAppReportForZSQDao.getRmIdByRegionId(regionId, "'区域经理','区域组长'", userIds);
        String senderIds = "";
        if (null != qyList) {
            for (int i = 0; i < qyList.size(); i++) {
                senderIds += "'" + qyList.get(i).getString("userId") + "',";
            }
        }
        if (!StringUtils.isBlank(senderIds) && senderIds.endsWith(",")) {
            senderIds = senderIds.substring(0, senderIds.length() - 1);
        } else {
            senderIds = "''";
        }
        String userParentIds = "";
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and id in (" + senderIds + ") and main = 1", new Object[]{});
        if (null != userList && userList.size() > 0) {
            for (int i = 0; i < userList.size(); i++) {
                userParentIds += "'" + userList.get(i).getString("parentId") + "',";
            }
        }
        if (!StringUtils.isBlank(userParentIds) && userParentIds.endsWith(",")) {
            userParentIds = userParentIds.substring(0, userParentIds.length() - 1);
        } else {
            userParentIds = "''";
        }
        List<JSONObject> dqList = newAppReportForZSQDao.getUserIdByRegionIdForPartTimeJob(regionId, "大区经理", userParentIds);
        String receiverIds = "";
        if (null != dqList) {
            for (int i = 0; i < dqList.size(); i++) {
                receiverIds += "'" + dqList.get(i).getString("userId") + "',";
            }
        }
        if (!StringUtils.isBlank(receiverIds) && receiverIds.endsWith(",")) {
            receiverIds = receiverIds.substring(0, receiverIds.length() - 1);
        }
        if (StringUtils.isBlank(receiverIds)) {
            receiverIds = "''";
        }
        if (StringUtils.isBlank(senderIds)) {
            senderIds = "''";
        }
        List<JSONObject> emilList = newAppReportForZSQDao.getEmailByUserIdAndRoleNameForRM(senderIds, receiverIds, dateTime, regionId);
        if (null != emilList && emilList.size() > 0) {
            for (int i = 0; i < emilList.size(); i++) {
                JSONObject object = emilList.get(i);
                String readerId = object.getString("readerId");
                if (StringUtils.isBlank(readerId)) {
                    String userRegionId = object.getString("regionId");
                    List<JSONObject> dqUserList = newAppReportForZSQDao.getUserIdByRegionIdForPartTimeJob(regionId, "大区经理", receiverIds);
                    if (null != dqUserList && dqUserList.size() > 0) {
                        readerId = dqUserList.get(0).getString("userId");
                    }
                    if (!StringUtils.isBlank(readerId)) {
                        object.put("readerId", readerId);
                        object.put("readerName", userDao.getById(readerId).getName());
                    }
                    if ("未发送".equals(object.getString("titleSend"))) {
                        Integer count = newAppReportForZSQDao.getSendEmail(object.getString("userId"), dateTime);
                        if (null != count && count != 0) {
                            object.put("titleSend", "已发送");
                        }
                    }
                }
            }
        }


        JSONObject result = new JSONObject();
        result.put("records", emilList);
        return result;

    }

    //区域组长工作报告
    @Override
    public JSONObject getEmailByUserIdForRTL(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String roleName = jsonParams.getString("roleName");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        dateTime = DateUtils.getyesterdayByDateTime(dateTime);

        StringBuffer condition = new StringBuffer();
        condition.append(" AND roleName ='区域组长'  AND v_sys_user.MAIN=1 \n");

        String senderIds = getRegionManagerByUserId(userId, condition, false);
        condition.delete(0, condition.length());
        condition.append(" AND roleName ='大区经理' \n");
        String receiverIds = getRegionManagerByUserId(userId, condition, false);

        if (StringUtils.isBlank(receiverIds)) {
            receiverIds = "''";
        }
        if (StringUtils.isBlank(senderIds)) {
            senderIds = "''";
        }
        List<JSONObject> list = newAppReportForZSQDao.getEmailForZSQ(userId, senderIds, receiverIds, dateTime);

        if (null != list && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject object = list.get(i);
                String readerId = object.getString("readerId");
                if (StringUtils.isBlank(readerId)) {
                    String regionId = object.getString("regionId");
                    List<JSONObject> dqList = newAppReportForZSQDao.getUserIdByRegionId(regionId, "大区经理", receiverIds);
                    if (null != dqList && dqList.size() > 0) {
                        readerId = dqList.get(0).getString("userId");
                    }
                    if (!StringUtils.isBlank(readerId)) {
                        object.put("readerId", readerId);
                        object.put("readerName", userDao.getById(readerId).getName());
                    }
                }
            }
        }
        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;

    }

    private static StringBuffer getRoleNamesByRoleName(String roleName) {
        List<String> roleNameList = new ArrayList();
        Map<String, Integer> roleNameMap = new HashMap<>();

        roleNameList.add("总经理");
        roleNameList.add("销售总监");
        roleNameList.add("区域总监");
        roleNameList.add("大区经理");
        roleNameList.add("区域组长");
        roleNameList.add("区域经理");
        roleNameMap.put("总经理", 0);
        roleNameMap.put("销售总监", 1);
        roleNameMap.put("区域总监", 2);
        roleNameMap.put("大区经理", 3);
        roleNameMap.put("区域组长", 4);
        roleNameMap.put("区域经理", 5);

        StringBuffer roleNames = new StringBuffer();
        int listIndex = 0;
        Integer index = roleNameMap.get(roleName);
        if (null == index) {
            listIndex = roleNameList.size();
        } else {
            listIndex = roleNameMap.get(roleName);
        }
        for (int i = listIndex; i < roleNameList.size(); i++) {
            roleNames.append("'" + roleNameList.get(i) + "'");
            if (i != roleNameList.size() - 1) {
                roleNames.append(",");
            }
        }
        if (roleNames.length() <= 0) {
            roleNames.append("''");
        }
        return roleNames;
    }

    @Override
    public JSONObject getTodayPlanByRoleName(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String roleName = jsonParams.getString("roleName");
        String regionId = "";
        if (jsonParams.containsKey("regionId")) {
            regionId = jsonParams.getString("regionId");

        }
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        dateTime = DateUtils.getyesterdayByDateTime(dateTime);

        StringBuffer condition = new StringBuffer();
        condition.append(" AND roleName in ('" + roleName + "') and main=1 \n");

        String userIds = getRegionManagerByUserId(userId, condition, false);

        if (!StringUtils.isBlank(regionId)) {
            List<JSONObject> qyList = newAppReportForZSQDao.getRmIdByRegionId(regionId, "'区域经理','区域组长'", userIds);
            String senderIds = "";
            if (null != qyList && qyList.size() > 0) {
                for (int i = 0; i < qyList.size(); i++) {
                    senderIds += "'" + qyList.get(i).getString("userId") + "',";
                }
            } else {
                userIds = "''";
            }
            if (!StringUtils.isBlank(senderIds) && senderIds.endsWith(",")) {
                userIds = senderIds.substring(0, senderIds.length() - 1);
            }
        }

        List<JSONObject> records = newAppReportForZSQDao.getTodayPlanByUserIdAndDateTimeForZSQ(userIds, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", records);
        return result;
    }

    private String getReader(String roleName, String regionId, String companyId) {
        List<String> roleNameList = new ArrayList();
        Map<String, Integer> roleNameMap = new HashMap<>();

        roleNameList.add("总经理");
        roleNameList.add("销售总监");
        roleNameList.add("区域总监");
        roleNameList.add("大区经理");
        roleNameList.add("区域组长");
        roleNameList.add("区域经理");
        roleNameMap.put("总经理", 0);
        roleNameMap.put("销售总监", 1);
        roleNameMap.put("区域总监", 2);
        roleNameMap.put("大区经理", 3);
        roleNameMap.put("区域组长", 4);
        roleNameMap.put("区域经理", 5);

        StringBuffer roleNames = new StringBuffer();
        int listIndex = 0;
        Integer index = roleNameMap.get(roleName);
        if (null != index) {
            listIndex = roleNameMap.get(roleName);
        } else {
            listIndex = -1;
            roleNames.append("'" + roleName + "'");
        }
        for (int i = listIndex; i >= 0; i--) {
            roleNames.append("'" + roleNameList.get(i) + "'");
            if (i != 0) {
                roleNames.append(",");
            }
        }
        if (roleNames.length() <= 0) {
            roleNames.append("''");
        }
        List<JSONObject> list = newAppReportForZSQDao.getNoUserRegionReader(regionId, roleNames.toString(), companyId);
        if (null != list && list.size() > 0) {
            return list.get(0).getString("userId");
        }
        return "";
    }

    private String getSupportReader(String roleName, String regionId, String companyId) {
        List<String> roleNameList = new ArrayList();
        Map<String, Integer> roleNameMap = new HashMap<>();

        roleNameList.add("销售管理");
        roleNameList.add("区域支持");

        roleNameMap.put("销售管理", 0);
        roleNameMap.put("区域支持", 1);

        StringBuffer roleNames = new StringBuffer();
        int listIndex = 0;
        Integer index = roleNameMap.get(roleName);
        if (null != index) {
            listIndex = roleNameMap.get(roleName);
        } else {
            listIndex = -1;
            roleNames.append("'" + roleName + "'");
        }
        for (int i = listIndex; i >= 0; i--) {
            roleNames.append("'" + roleNameList.get(i) + "'");
            if (i != 0) {
                roleNames.append(",");
            }
        }
        if (roleNames.length() <= 0) {
            roleNames.append("''");
        }
        List<JSONObject> list = newAppReportForZSQDao.getNoUserRegionReader(regionId, roleNames.toString(), companyId);
        if (null != list && list.size() > 0) {
            return list.get(0).getString("userId");
        }
        return "";
    }

}
